#include "Vertex3D.h"
#include "Triangle.h"
#include "Scene.h"

#include <SDL/SDL.h>

#include <GL/gl.h>
#include <GL/glu.h>

#include <iostream>

using namespace std;

static void
initGL
(int w, int h)
{
  glViewport(0, 0, w, h);
  glClearColor(0.4, 0.5, 1.0, 0.0);
  
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(45.0, (GLfloat)w/(GLfloat)h, 0.01, 100.0);
  glMatrixMode(GL_MODELVIEW);
  
  glEnable(GL_DEPTH_TEST);
}

static SDL_Surface*
initSDL
(int w, int h, const char *caption)
{
  SDL_Surface* sf = 0;
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
    cerr << "SDL_Init: " << SDL_GetError() << endl;
    return 0;
  }

  sf = SDL_SetVideoMode(800, 600, 0, SDL_OPENGL | SDL_DOUBLEBUF);
  if (sf == 0) {
    cerr << "SDL_SetVideoMode: " << SDL_GetError() << endl;
    SDL_Quit();
    return 0;
  }

  SDL_EnableKeyRepeat(40, 40);

  SDL_WM_SetCaption(caption, 0);

  // Initialize OpenGL.
  initGL(w, h);

  return sf;
}

static uint32_t
frame_update
(uint32_t interval, void *param)
{
	SDL_Event ev;
	ev.type = SDL_USEREVENT;
	ev.user.code = 0;

	SDL_PushEvent(&ev);
	return interval;
}

static void
show_help()
{
}

static void
show_controls()
{
}

int
main
(int argc, char ** argv)
{
  bool done;
  bool fs(false);

  // Initiliaze SDL.
  SDL_Surface *sf = initSDL(800, 600, "OpenGL / SDL integration");
  // Full screen?
  if (fs) SDL_WM_ToggleFullScreen(sf);

  // Adds a timer which will call a callback after 
  // the specified number of milliseconds has elapsed.
  SDL_AddTimer(40, frame_update, 0);

  SDL_Event event;

  done = false;

  // TODO.
  // INSTANTIATE THE TRIANGLE AND THE SCENE.

  while (!done) {

    if (SDL_PollEvent(&event)) {

      if (event.type == SDL_QUIT) done = true;

      else if (event.type == SDL_KEYDOWN) {

	uint32_t sym = event.key.keysym.sym;

	switch (sym) {
	  // Exit when typing 'q' or ESC.
	case SDLK_q:
	case SDLK_ESCAPE:
	  done = true;
	  break;

	  // Full Screen when typing 'f'.
	case SDLK_f:
	  SDL_WM_ToggleFullScreen(sf);
	  break;

	  // Default event other than 'f', 'q' or ESC.
	default:
	  printf("Event handler...");
	  // Send the event to the scene handler.
	  // TODO: uncomment after instantiating the scn object.
	  // scn.handler(event);
	}// End switch.

      } else {
	// Send the event to the scene handler.
	// TODO: uncomment after instantiating the scn object.
	// scn.handler(event);
      } // End else.

    } // End else key event.

  }// End while

  SDL_Quit();
  return 0;
}
